import req from '@utils/request';
import {
  FileImageOutlined,
  MessageOutlined,
  ShareAltOutlined,
  SmileOutlined
} from '@ant-design/icons';
import { Avatar, Button, Card, Input, Popover, Tabs, Upload, message, Image, Collapse, Modal } from 'antd';
import { useState ,useEffect} from 'react';
import './index.less';
import MomentList from './components/moment-list';
import CommentList from './components/comment-list';
const { Meta } = Card;
const { TextArea } = Input;
import { PlusOutlined } from '@ant-design/icons';

const Circle = () => {
  const userInfoStorage = localStorage.getItem('userInfo')
  const { tokenValue = '' } = userInfoStorage ? JSON.parse(userInfoStorage) : {}
  const [hasFocus, setHasFocus] = useState(false);
  const [context, setComment] = useState('');
  const [is_changeCircle, setChangeCircle] = useState();
  const [changeCircleId, setChangeCircleId] = useState('-99');
  const [circleList, setCircleList] = useState([]);
  const [fileList, setFileList] = useState([{ uid: Number, name: String, status: String, url: String }]);
  const [momentList, setMomentList] = useState([]);
  const [openComment, setOpenComment] = useState([]);
  const [commentPicList, setCommentPicList] = useState([]);
  const [commentContent, setCommentContent] = useState('');
  const [toMetentId, setToMotentId] = useState('');
  const [toTargetId, setToTargetId] = useState('');
  const [actveCircleId, setActiveCircleId] = useState();
  // 论屎山是如何形成的~
  useEffect(() => {
    getMomentListById()
  }, [])
  //================================== 评论相关==================================
  let commentSave = {
    momentId: toMetentId,
    replyType: 1,
    targetId: toTargetId,
    content: commentContent,
    picUrlList: commentPicList.map(item => item.url)
  }
  const save = () => {
    req({
      method: 'post',
      url: '/share/comment/save',
      data: commentSave
    }, '/circle').then(res => {
      if (!res.success) return;
      message.success("评论成功");
      openCommentChange(toMetentId)
      setToMotentId();
      setToTargetId();
      setCommentPicList([]);
      setCommentContent();
      getMomentListById(actveCircleId)
    })
  };
  const handleOk = (montentId) => {
    save();
    openCommentChange(montentId)
  };
  const handleCancel = (montentId) => {
    message.warning("评论取消！");
    setCommentPicList([]);
    openCommentChange(montentId)
  };

  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button"
    >
      <PlusOutlined />
      <div
        style={{
          marginTop: 4,
        }}
      >
        Upload
      </div>
    </button>
  );
  // 评论按钮初始状态
  const commentShow = () => {
    if (!momentList) return;
    setOpenComment(momentList.map((acc, item) => {
      acc[item.id] = false;
      return acc;
    })
    )
  };
  // 评论状态改变
  const openCommentChange = (circleId) => {
    setOpenComment(pre => ({
      ...pre,
      [circleId]: !openComment[circleId]
    }))
  }
  const handleChange = ({ file }) => {
    if (file.status === 'done') {
      // 文件上传成功后，可以在这里处理返回的数据
      console.log('File uploaded successfully:', file.name);
      commentPicList.push({ uid: file.uid, name: file.name, status: file.status, url: file.response.data })
    } else if (file.status === 'removed') {
      const newFileList = commentPicList.filter(f => f != file.response.data);
      setCommentPicList(newFileList);
      console.log('File removed:', file.name);
    }
  }
const deleteComment = (montentId) => {
  getMomentListById(montentId)
}

  // ==============================获取圈子列表===============================
  const get_circle_list = () => {
    req({
      method: 'get',
      url: '/share/circle/list'
    }, '/circle').then(res => {
      if (!res.success) return;
      setCircleList(res.data);
      commentShow()
    });
  };
  // ===============================动态相关================================
  let upload_circle = {
    circleId: changeCircleId,
    content: context,
    picUrlList: fileList.map(item => item.url),
  };
  // 获取动态
  const getMomentListById = (id) => {
    req({
      method: 'post',
      url: '/share/moment/getMoments',
      data: {
        circleId: actveCircleId,
        // pageNo: 1,
        // pageSize: 10
      }
    }, '/circle').then(res => {
      if (!res.success) return;
      setMomentList(res.data.result);
      setActiveCircleId(id)
    });
  };
  // 图片上传成功回调函数
  const handleFileChange = ({ file }) => {
    if (file.status === 'done') {
      console.log('File uploaded successfully:', file.name);
      fileList.push({ uid: file.uid, name: file.name, status: file.status, url: file.response.data })
    } else if (file.status === 'removed') {
      const newFileList = fileList.filter(f => f != file.response.data);
      setFileList(newFileList);
      console.log('File removed:', file.name);
    }
  };
  // 是否可提交
  const toggleFocus = (flag) => {
    setHasFocus(!flag);
  };

  // 文本框内容回调
  const onChange = e => {
    setComment(e.target.value);
  };
  const saveCircle = () => {
    req({
      method: 'post',
      url: '/share/moment/save',
      data: upload_circle
    }, '/circle').then(res => {
      if (!res.success) return;
      message.success('发布成功');
      setComment('');
      setFileList([]);
      setChangeCircle(undefined);
      setChangeCircleId('-99');
      setTimeout(() => {
        window.location.reload()
      }, 1000)
    })
  }

  // 点击动画
  const divStyle = {
    width: '50%',
    cursor: 'pointer', // 添加鼠标指针样式
    transition: 'background-color 0.3s', // 添加过渡效果
  };
  const renderPopContent = () => {
    return (
      <Tabs
        tabPosition='left'
        size='small'
        items={
          circleList.map(circle => ({
            label: circle.circleName,
            key: circle.id,
            children:
              <div className='pop-content'>
                {
                  circle.children.map(childrens =>
                    <div className='pop-content-item' key={childrens.id}
                      onClick={() => { setChangeCircle(childrens.circleName); setChangeCircleId(childrens.id); }}>
                      <img src={childrens.icon} className='item-img' />
                      <span className='item-name'>{childrens.circleName}</span>
                    </div>
                  )
                }
              </div>
          }))
        }
      />
    );
  };

  return (
    <div className='circle-box'>
      <Card>
        <div className={`top-input-card ${hasFocus ? 'card-focus' : ''}`}>
          <TextArea
            showCount
            maxLength={1000}
            onChange={onChange}
            value={context}
            placeholder='与圈友们分享你的个人经验'
            style={{
              height: 120,
              resize: 'none',
              border: 'none',
              backgroundColor: '#f2f3f5',
              boxShadow: 'none'
            }}
            className='top-text-area'
            onFocus={() => toggleFocus(false)}
            onBlur={() => toggleFocus(true)}
          />
          <Popover placement='bottomLeft' trigger='click' content={renderPopContent}>
            <div className='choose-circle' onClick={get_circle_list}>{is_changeCircle ? is_changeCircle : '选择圈子'} {'>'}</div>
          </Popover>
        </div>
        <div className='publish-options'>
          <div className='left-box'>
            <div>
              <SmileOutlined />
              <span style={{ marginLeft: '8px' }}>表情</span>
            </div>
            <div>
              <Upload
                name='uploadFile'
                listType='picture-card'
                className='avatar-uploader'
                accept='image/*'
                showUploadList={true}
                withCredentials
                action='/oss/upload'
                headers={{
                  satoken: tokenValue
                }}
                // fileList={fileList}
                data={{
                  bucket: 'community-club',
                }}
                onChange={handleFileChange}
              // onRemove={handleRemove}
              >
                <FileImageOutlined />图片
              </Upload>
            </div>
          </div>
          <div className='right-box'>
            <Button type='primary' disabled={!context.length} onClick={saveCircle}>
              发布
            </Button>
          </div>
        </div>
      </Card>
      <Card>
        <MomentList fromChildrenCircleId={getMomentListById} />
      </Card>
      {/* 动态 */}
      {momentList.map(item => (
        <Card key={item.id}
          style={{ marginTop: '10px' }}>
          <Meta
            avatar={<Avatar src={item.userAvatar} size={48} />}
            title={item.userName}
            description={item.createdTime}
            style={{ padding: '0px' }}
          />
          <div style={{ marginTop: '20px' }}></div>
          <div dangerouslySetInnerHTML={{ __html: item.content }}></div>
          <div style={{ marginTop: '10px' }}></div>
          {item.picUrlList && item.picUrlList.length > 0 ? (item.picUrlList.map(item1 => (
            <Image
              key={item1}
              preview={true}
              src={item1}
              width={'16%'}
              height={'auto'}
            />
          ))) : ''}
          <div className='comment-box'>

          </div>
          <div style={{ marginTop: '30px', display: 'flex', textAlign: 'center' }}>
            <div style={{ width: '50%', borderRight: '1px solid #ccc' }}>
              <ShareAltOutlined />
              <span style={{ marginLeft: 8 }}>分享</span>
            </div>
            <div style={{ width: '50%' }, divStyle} onClick={() => {
              openCommentChange(item.id);
              setToMotentId(item.id); setToTargetId(item.id)
            }}>
              <div style={{ color: openComment[item.id] ? '#3c6eee' : 'black' }}>
                <MessageOutlined />
                <span style={{ marginLeft: 8 }}>{item.replyCount}评论</span>
              </div>
            </div>
            <Modal title={"评论：" + item.userName} open={item.replyCount < 1 && openComment[item.id]} onOk={() => handleOk(item.id)} onCancel={() => handleCancel(item.id)}>
              <TextArea rows={4} placeholder="输入评论内容" maxLength={6} onChange={e => setCommentContent(e.target.value)} />
              <div style={{ marginTop: '20px' }}></div>
              <Upload
                name='uploadFile'
                listType='picture-card'
                className='avatar-uploader'
                accept='image/*'
                showUploadList={true}
                withCredentials
                action='/oss/upload'
                headers={{
                  satoken: tokenValue
                }}
                data={{
                  bucket: 'community-club',
                }}
                onChange={handleChange}
              >
                {commentPicList.length >= 3 ? null : uploadButton}
              </Upload>
            </Modal>
          </div>
          {openComment[item.id] ? <CommentList circleId={item.id} deleteComment={deleteComment}/> : ''}
        </Card>
      ))}
    </div>
  );
};

export default Circle;